/**
 * \license
 * Copyright Lassi Marttala 2013
 * 
 * This file is part of dlt2jpa.
 *
 * dlt2jpa is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * dlt2jpa is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with dlt2jpa.  If not, see <http://www.gnu.org/licenses/>.
 */

package net.fizzl.dlt.message.parser;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

import net.fizzl.dlt.message.DltPayloadArgument;
import net.fizzl.dlt.message.DltPayloadArgumentTypeInfo;
import net.fizzl.dlt.message.DltPayloadArgument.ArgumentType;

public class DltPayloadArgumentParser {

	public DltPayloadArgument fromByteArray(byte data[]) {
		DltPayloadArgument ret = new DltPayloadArgument();
		ByteBuffer src = ByteBuffer.wrap(data);
		src.order(byteOrder);
		DltPayloadArgumentTypeInfo ai = DltPayloadArgumentTypeInfo.fromInt(src.getInt());
		
		byte d[] = new byte[0];
		switch (ai.getType()) {
		case TypeBoolean:
		case TypeSignedInteger:
		case TypeUnsignedInteger:
		case TypeFloat:
			if (ai.getTypeLength() > 0) {
				d = new byte[ai.getTypeLength()];
				src.get(d);
				ret.setData(d);
				ret.setTypeLength(ai.getTypeLength());
			}
			break;
		case TypeRawData:
		case TypeString:
		case TypeTraceInfo: {
				short len = src.getShort();
				d = new byte[len];
				ret.setData(d);
			}
			break;
		default:
			throw new UnsupportedOperationException();
		}

		ret.setLength(src.position());
		
		ByteBuffer b = ByteBuffer.wrap(d);
		b.order(byteOrder);
		
		// Set the actual content
		switch(ai.getType()) {
		case TypeBoolean:
			Boolean val = false;
			byte by = b.get();
			if(by > 0) {
				val = true;
			}
			ret.setValue(val);
			ret.setType(ArgumentType.TypeBool);
			break;
		case TypeFloat:
			break;
		case TypeRawData:
			break;
		case TypeSignedInteger:
			break;
		case TypeString:
			break;
		case TypeTraceInfo:
			break;
		case TypeUnknown:
			break;
		case TypeUnsignedInteger:
			break;
		default:
			break;
		
		}
		return ret;
	}
	
	public DltPayloadArgumentParser(ByteOrder byteOrder) {
		this.byteOrder = byteOrder;
	}

	private ByteOrder byteOrder = ByteOrder.LITTLE_ENDIAN;
}
